<template>
  <div class="body">
    <el-card class="box-card">
      <el-form
        :rules="rules"
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="年级" prop="gradeId">
          <el-select size="small" v-model="ruleForm.gradeId" placeholder="年级">
            <el-option
              :label="item.typeName"
              :value="item.typeId"
              v-for="(item, index) in gradeList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学科" prop="subjectId">
          <el-select
            size="small"
            v-model="ruleForm.subjectId"
            placeholder="学科"
            value-key="courseId"
          >
            <el-option
              :label="item.typeName"
              :value="item.typeId"
              v-for="(item, index) in subjects"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="试卷类型" prop="paperType">
          <el-select
            size="small"
            v-model="ruleForm.paperType"
            placeholder="请选择试卷类型"
            value-key="typeId"
          >
            <el-option
              :label="item.typeName"
              :value="item.typeId"
              v-for="(item, index) in typeList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="限定时间" v-if="ruleForm.paperType == '52'">
          <el-date-picker
            v-model="times"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeTimes"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="试卷名称" prop="paperName">
          <el-input size="small" v-model="ruleForm.paperName"></el-input>
        </el-form-item>
        <el-form-item
          :label="`标题` + (index + 1)"
          prop="title"
          v-for="(item, index) in title"
          :key="index"
        >
          <div class="titles">
            <el-input
              width="400"
              size="small"
              v-model="item.titleName"
            ></el-input>
            <div style="width: 100px; margin-left: 10px">
              <el-link
                type="primary"
                :underline="false"
                @click="openSubjectsShow(index)"
                >添加题目</el-link
              >
            </div>
            <div style="width: 100px">
              <el-link
                v-if="index != 0"
                type="primary"
                :underline="false"
                @click="delSubject(index)"
                >删除</el-link
              >
            </div>
          </div>
          <el-card style="margin-top: 12px" v-if="item.questions.length > 0">
            <el-row v-for="(ite, ind) in item.questions" :key="ind">
              <el-col :span="2">题目{{ ind + 1 }}</el-col>
              <el-col :span="20">
                <div>{{ ite.questions }} {{ ite.questionsStems }}</div>
                <div>
                  <span
                    style="margin-left: 10px"
                    v-for="(ele, i) in ite.answerFixed"
                    :key="i"
                  >
                    {{ ele.optionsName }}. {{ ele.content }}</span
                  >
                </div>
              </el-col>
              <el-col :span="2">
                <el-link
                  type="primary"
                  :underline="false"
                  @click="delSubjects(index, ind)"
                  >删除</el-link
                >
              </el-col>
            </el-row>
          </el-card>
        </el-form-item>
        <el-form-item label="建议时长" prop="duration">
          <el-input-number
            v-model="ruleForm.duration"
            size="small"
            :min="1"
            :max="120"
            label="分钟"
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="submit"
            >提交</el-button
          >
          <el-button size="small" @click="Reset">重置</el-button>
          <el-button type="success" size="small" @click="addTitle"
            >添加标题</el-button
          ><el-button size="small" @click="$router.go(-1)">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 添加题目模态框 -->
    <el-dialog :visible.sync="subjectsShow" width="60%">
      <el-table
        style="margin-top: 10px; width: 100%"
        :data="tableData"
        border
        @selection-change="change"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column
          property="questionsId"
          label="序号"
          width="100"
        ></el-table-column>
        <el-table-column
          property="typeName"
          label="题型"
          width="200"
        >
          <!-- <template slot-scope="scope">
            <span>{{scope}}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          property="questionsStems"
          label="题干"
        ></el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="subjectsShow = false">取 消</el-button>
        <el-button size="small" type="primary" @click="addSubject"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getQuertionBankListApi } from "@/api/onlinehomework/questionbank.js";
import {
  addTextPagerApi,
  getTextPagerListApi,
  editTextPagerApi,
} from "../../../api/onlinehomework/textPager.js";
import { getGradeListApi } from "../../../api/basics/teachingPlan.js";
import { getClassifyListApi } from "../../../api/basics/classify.js";
export default {
  data() {
    return {
      times: "",
      ruleForm: {
        //   年级
        gradeId: "",
        // 学科
        subjectId: "",
        // 试卷类型
        paperType: "",
        // 试卷名称
        paperName: "",
        // 建议时长
        duration: "",
      },
      // 开始时间
      startTime: "",
      // 结束时间
      endTime: "",
      //   表单校验
      rules: {
        gradeId: [{ required: true, message: "请选择年级", trigger: "change" }],
        subjectId: [
          { required: true, message: "请选择学科", trigger: "change" },
        ],
        paperType: [
          { required: true, message: "请选择试卷类型", trigger: "change" },
        ],
        startTime: [
          {
            type: "date",
            required: true,
            message: "请选择开始日期",
            trigger: "change",
          },
        ],
        endTime: [
          {
            type: "date",
            required: true,
            message: "请选择结束日期",
            trigger: "change",
          },
        ],
        paperName: [
          { required: true, message: "请输入试卷名称", trigger: "blur" },
        ],
        titleName: [{ required: true, message: "请输入标题", trigger: "blur" }],
        duration: [
          { required: true, message: "请输入建议时长", trigger: "blur" },
        ],
      },
      //   标题数据
      title: [{ titleName: "", questions: [] }],
      //   添加题目模态框显示隐藏
      subjectsShow: false,
      //   题目的索引值
      index: "",
      //   添加题目搜索id
      code: "",
      //   添加题目搜索题型
      questionType: "",
      //   分页页数
      pageNum: 1,
      //   分页条数
      pageSize: 5,
      total: 0,
      //   模态框表格数据
      tableData: [],
      //   选中的题目放到subjectList里面
      subjectList: [],
      //   年级选择框模拟数据
      gradeList: [],
      //   学科选择框模拟数据
      subjects: [],
      //   试卷类型选择框模拟数据
      typeList: [],
      //   题型选择框模拟数据
      questionTypeList: ["单选题", "多选题", "判断题", "问答题"],
    };
  },
  mounted() {
    if (this.$route.query.id) {
      this.getPagerList();
    }
    this.getKecheng();
  },
  methods: {
    changeTimes(e) {
      this.startTime = this.formatDate(e[0]);
      this.endTime = this.formatDate(e[1]);
      console.log(this.startTime, this.endTime);
    },
    formatDate(d) {
      var date = new Date(d);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    async getPagerList() {
      const data = await getTextPagerListApi({ id: this.$route.query.id });
      console.log(data.rows, "rows");
      this.ruleForm = {
        gradeId: data.rows[0].gradeId,
        // 学科
        subjectId: data.rows[0].subjectId,
        // 试卷类型
        paperType: data.rows[0].paperType,
        // 试卷名称
        paperName: data.rows[0].paperName,
        // 建议时长
        duration: data.rows[0].duration,
      };
      this.title = JSON.parse(data.rows[0].title);
      // 开始时间
      this.startTime = data.rows[0].startTime;
      // 结束时间
      this.endTime = data.rows[0].endTime;
      this.times = [this.startTime, this.endTime];
      console.log(this.ruleForm, "ruleForm");
    },
    //   重置
    Reset() {
      this.ruleForm = {
        grade: "",
        // 学科
        subject: "",
        type: "",
        name: "",
        time: "",
      };
      this.title = [{ titleName: "", questions: [] }];
    },
    emoveHtmlStyle(html) {
      let relStyle = /style\s*?=\s*?([‘"])[\s\S]*?\1/g; //去除样式
      let relTag = /<.+?>/g; //去除标签
      let relClass = /class\s*?=\s*?([‘"])[\s\S]*?\1/g; // 清除类名
      let newHtml = "";
      if (html) {
        newHtml = html.replace(relStyle, "");
        newHtml = newHtml.replace(relTag, "");
        newHtml = newHtml.replace(relClass, "");
      }
      return newHtml;
    },
    //   结束时间选择
    changeDate2(e) {
      let date = e.getFullYear() + "-" + (e.getMonth() + 1) + "-" + e.getDate();
      console.log(date);
      this.endTime = date;
    },
    //   开始时间选择
    changeDate1(e) {
      let date = e.getFullYear() + "-" + (e.getMonth() + 1) + "-" + e.getDate();
      console.log(date);
      this.startTime = date;
    },
    async getKecheng() {
      const datas = await getGradeListApi({ parentId: 130 });
      const data1 = await getGradeListApi({ parentId: 55 });
      const data2 = await getClassifyListApi({ parentId: 50 });
      this.typeList = data2.rows;
      this.gradeList = data1.rows;
      this.subjects = datas.rows;
    },
    //   提交试卷
    submit() {
      this.$refs.ruleForm.validate(async (valid) => {
        console.log(this.title);
        if (valid) {
          let a = this.title.every((item) => {
            return item.titleName == "";
          });
          let b = this.title.every((item) => {
            console.log(item.questions);
            return item.questions.length == 0;
          });
          console.log(a, "aaaaaaaaaaaaaaaa");
          console.log(b, "bbbbbbbbbbbbbbbb");
          if (a) {
            this.$message({
              type: "error",
              message: "请填写标题!",
            });
            return false;
          }
          if (b) {
            this.$message({
              type: "error",
              message: "请添加题目!",
            });
            return false;
          }
          this.ruleForm.title = this.title;
          if (this.$route.query.id) {
            this.ruleForm.id = this.$route.query.id;
            if (this.ruleForm.paperType == "52") {
              (this.ruleForm.startTime = this.startTime),
                (this.ruleForm.endTime = this.endTime);
            }
            const data = await editTextPagerApi(this.ruleForm);
            if (data.code == 200) {
              this.$router.push("/onlinehomework/testpaper/testPaperList");
              this.$message({
                type: "success",
                message: "提交成功!",
              });
            }
          } else {
            if (this.ruleForm.paperType == "52") {
              (this.ruleForm.startTime = this.startTime),
                (this.ruleForm.endTime = this.endTime);
            }
            const data = await addTextPagerApi(this.ruleForm);
            if (data.code == 200) {
              this.$router.push("/onlinehomework/testpaper/testPaperList");
              this.$message({
                type: "success",
                message: "提交成功!",
              });
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //   删除题目
    delSubjects(index, ind) {
      this.$confirm("此操作将永久删除该题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.title[index].questions.splice(ind, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //   删除标题
    delSubject(index) {
      this.$confirm("此操作将永久删除该标题, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.title.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分页页码改变
    handleCurrentChange(e) {
      console.log(e, "页码");
      this.pageNum = e;
      this.openSubjectsShow();
    },
    // 改变分页条数
    handleSizeChange(e) {
      console.log(e, "条数");
      this.pageSize = e;
      this.openSubjectsShow();
    },
    // 确定添加题目
    addSubject() {
      this.title[this.index].questions.push(...this.subjectList);
      console.log(this.title);
      this.subjectsShow = false;
      this.subjectList = [];
      this.questionType = "";
      this.code = "";
      this.$refs.multipleTable.clearSelection();
    },
    // 选择题目
    change(e) {
      console.log(e);
      let aa = [];
      e.forEach((item) => {
        let bb = {};
        bb.questions = item.questionsName;
        bb.questionsStems = item.questionsStems;
        bb.answerFixed = item.options;
        aa.push(bb);
      });
      this.subjectList = aa;
    },
    // 显示添加题目模态框
    async openSubjectsShow(i) {
      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
      };
      const data2 = await getClassifyListApi({ parentId: 183 });
      console.log(data2.rows, "152000000000");
      const datas = await getQuertionBankListApi(params);
      console.log(datas.rows);
      this.subjectsShow = true;
      this.tableData = datas.rows;
      this.total = datas.total;
      datas.rows.forEach((item) => {
        console.log(item, "/85200000000000");
        if(item.questionsType == '0') {
          item.questionsType = '单选题'
        }else if(item.questionsType == '1'){
          item.questionsType = '多选题'
        }else if(item.questionsType == '2'){
          item.questionsType = '判断题'
        }else if(item.questionsType == '3'){
          item.questionsType = '填空题'
        }else if(item.questionsType == '4'){
          item.questionsType = '简答题'
        }
        console.log(item.options,'111111111');
        // item.options = JSON.parse(item.options)
        item.questionsStems = this.emoveHtmlStyle(item.questionsStems);
        // if(item.options != null && item.options.length > 0) {
        //   console.log(item,'000000');
          item.options = JSON.parse(item.options);
          data2.rows.forEach((ite) => {
            if (ite.typeId == item.questionsType) {
              item.questionsType = ite.typeName;
            }
          });
        // }
      });
      this.index = i;
    },
    // 添加标题
    addTitle() {
      this.title.push({
        titleName: "",
        questions: [],
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.body {
  padding: 0 30px;
  .titles {
    display: flex;
  }
}
</style>
